#include "Bone.h"
#include "Model.h"

Bone::Bone(std::shared_ptr<BoneAsset> boneAsset)
{
    this->name = boneAsset->name;
    this->id = boneAsset->id;
    this->offset = boneAsset->restPose;
    this->restOffset = boneAsset->restPose;
    this->baseRestOffsetInverse = boneAsset->restPoseInv;
    this->bindOffset = boneAsset->bindPose;
}

void Bone::UpdateOffset(std::shared_ptr<std::vector<glm::mat4>> animMat4s,
                        std::shared_ptr<std::vector<glm::mat4>> outPutMat4s,
                        std::shared_ptr<std::vector<glm::mat4>> OffsetPutMat4s,
                        glm::mat4 globalOffset)
{
    if (id == -1 || id >= animMat4s->size())
    {
        offset = restOffset;
    } else {
        offset = ((*animMat4s)[id] * baseRestOffsetInverse) * restOffset;
    }

    if (parent)
        offset = parent->offset * offset;
    else
        offset = globalOffset * offset;

    if (id != -1)
    {
        (*outPutMat4s)[id] = offset * bindOffset;
        (*OffsetPutMat4s)[id] = offset;
    }
    for (auto child : children)
        child->UpdateOffset(animMat4s, outPutMat4s, OffsetPutMat4s, globalOffset);
}